package com.future.mayi.activity;

import android.app.Activity;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.bumptech.glide.Glide;
import com.future.baselib.entity.BaseResponse;
import com.future.baselib.entity.DefaultResponse;
import com.future.baselib.utils.ApiCst;

import com.future.baselib.utils.HttpRequest;
import com.future.baselib.view.CircleImageView;
import com.imnjh.imagepicker.SImagePicker;
import com.imnjh.imagepicker.activity.PhotoPickerActivity;
import com.future.mayi.R;
import com.future.mayi.app.App;
import com.future.mayi.response.UploadFileResponse;
import com.future.mayi.response.UserInfoResponse;
import com.future.mayi.utils.HCUtils;
import com.future.mayi.utils.SharedPreferencesUtils;
import com.future.mayi.utils.imageselectcache.CacheManager;
import com.future.mayi.utils.perimission.DefaultRationale;
import com.future.mayi.utils.perimission.PermissionSetting;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;

public class UserInfoActivity extends BaseTitleActivity {


    @BindView(R.id.iv_head_img)
    CircleImageView ivHeadImg;
    @BindView(R.id.ll_head_img)
    LinearLayout llHeadImg;
    @BindView(R.id.tv_nick_name)
    TextView tvNickName;
    @BindView(R.id.ll_nick_name)
    LinearLayout llNickName;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.ll_sex)
    LinearLayout llSex;
    @BindView(R.id.tv_birthday)
    TextView tvBirthday;
    @BindView(R.id.ll_birthday)
    LinearLayout llBirthday;
    @BindView(R.id.ll_login)
    TextView llLogin;

    private int sex;
    private String birthday, nickName, headImg;

    @Override
    protected void initTopBar() {
        initBack();
        getTitleText().setText("个人信息");
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_user_info);
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initDates() {
        sex = (int) SharedPreferencesUtils.get(UserInfoActivity.this, SharedPreferencesUtils.SpEnum.LoginSex, 0);
        birthday = (String) SharedPreferencesUtils.get(UserInfoActivity.this, SharedPreferencesUtils.SpEnum.LoginBirthday, "");
        nickName = (String) SharedPreferencesUtils.get(this, SharedPreferencesUtils.SpEnum.LoginNickName, "");
        tvSex.setText(sex == 0 ? "女" : "男");
        tvNickName.setText(TextUtils.isEmpty(nickName) ? "" : nickName);
        tvBirthday.setText(TextUtils.isEmpty(birthday) ? "" : birthday);
        headImg = (String) SharedPreferencesUtils.get(this, SharedPreferencesUtils.SpEnum.LoginHeadImg, "");

        HCUtils.loadWebImg(mContext, ivHeadImg, headImg);
    }

    @Override
    protected void initListener() {

    }


    @OnClick({R.id.ll_head_img, R.id.ll_nick_name, R.id.ll_sex, R.id.ll_birthday, R.id.ll_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_head_img:
                selectHead();
                break;
            case R.id.ll_nick_name:
                Intent intent = new Intent(this, EdtNickNameActivity.class);
                intent.putExtra("nickName", tvNickName.getText().toString());
                startActivityForResult(intent, EDT_NICK_NAME);
                break;
            case R.id.ll_sex:
                selectSex();
                break;
            case R.id.ll_birthday:
                selectDay();
                break;
            case R.id.ll_login:
                loginOut();
                App.clear();
                finish();
                break;
        }
    }


    private List<String> sexList;
    private OptionsPickerView sexDialog;

    private void selectSex() {
        if (sexDialog == null) {
            sexList = new ArrayList<>();
            sexList.add("女");
            sexList.add("男");
            sexDialog = new OptionsPickerView.Builder(UserInfoActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    dissmissLoadingDialog();
                    if (!TextUtils.equals(tvSex.getText(), sexList.get(options1))) {
                        changeInfo(String.valueOf(options1), 4);
                    }
                }
            }).setCancelColor(getResources().getColor(R.color.main_text_color))
                    .setSubmitColor(getResources().getColor(R.color.main_color))
                    .setContentTextSize(20)
                    .setTitleText("请选择性别")
                    .build();
            sexDialog.setPicker(sexList);
        }
        sexDialog.show();
    }


    private TimePickerView pvTime;

    private void selectDay() {
        if (pvTime == null) {
            Calendar endCalendar = Calendar.getInstance();
            endCalendar.setTime(new Date());
            pvTime = new TimePickerView.Builder(UserInfoActivity.this, new TimePickerView.OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(date);
                    int year = calendar.get(Calendar.YEAR);//获取年份
                    int month = calendar.get(Calendar.MONTH) + 1;//获取月份
                    int day = calendar.get(Calendar.DATE);//获取日
                    String time = year + "-" + (month < 10 ? "0" + month : month) + "-" + day;
                    changeInfo(time, 3);
                }
            }).setTitleText("请选择生日").setRangDate(null, endCalendar).setType(new boolean[]{true, true, true, false, false, false}).build();
        }
        pvTime.show();
    }


    private DefaultRationale mRationale;
    private PermissionSetting mSetting;
    public static final int REQUEST_CODE_IMAGE = 100;
    public static final int EDT_NICK_NAME = 200;

    private void selectHead() {
        if (mRationale == null) {
            mRationale = new DefaultRationale();
        }
        if (mSetting == null) {
            mSetting = new PermissionSetting(this);
        }
        final String path = CacheManager.getInstance().getImageInnerCache().getAbsolutePath("headImage.png");
        AndPermission.with(this)
                .permission(Permission.CAMERA, Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE)
                .rationale(mRationale)
                .onGranted(new Action() {
                    @Override
                    public void onAction(List<String> permissions) {
                        SImagePicker
                                .from(UserInfoActivity.this)
                                .maxCount(1)
                                .rowCount(3)
                                .showCamera(true)
                                .pickMode(SImagePicker.MODE_AVATAR)
                                .cropFilePath(path)
                                .forResult(REQUEST_CODE_IMAGE);
                    }
                })
                .onDenied(new Action() {
                    @Override
                    public void onAction(@NonNull List<String> permissions) {
                        if (AndPermission.hasAlwaysDeniedPermission(UserInfoActivity.this, permissions)) {
                            mSetting.showSetting(permissions);
                        }
                    }
                })
                .start();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_CODE_IMAGE) {
                final ArrayList<String> pathList = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT_SELECTION);
                if (pathList != null && pathList.size() > 0 && (!TextUtils.isEmpty(pathList.get(0)))) {
                    String mHeadLocalPath = pathList.get(0);
                    HCUtils.loadWebImg(UserInfoActivity.this, ivHeadImg, mHeadLocalPath);
                    uploadImg(mHeadLocalPath);
                }
            } else if (requestCode == EDT_NICK_NAME) {
                String nickName = data.getStringExtra("nickName");
                changeInfo(nickName, 1);
            }
        }
    }


    /**
     * code
     * 1.用户昵称  nickname
     * 2.用户头像url  avatar
     * 3.生日 格式“yyyy-mm-dd”  birthday
     * 4.性别 0-女 1-男  gender
     */
    @SuppressWarnings("unchecked")
    private void changeInfo(final String content, final int code) {
        showLoadingDialog();
        TreeMap<String, Object> params = new TreeMap<>();
        params.put("token", App.getToken(mContext));
        String key = null;
        switch (code) {
            case 1:
                key = "nickname";
                break;
            case 2:
                key = "avatar";
                break;
            case 3:
                key = "birthday";
                break;
            case 4:
                key = "gender";
                break;
        }
        if (key == null)
            return;
        params.put(key, content);
        new HttpRequest<DefaultResponse>()
                .with(this)
                .setApiCode(ApiCst.setUserInfo)
                .addParams(params)
                .setListener(new HttpRequest.OnNetworkListener<DefaultResponse>() {
                    @Override
                    public void onSuccess(DefaultResponse baseResponse) {
                        toast(baseResponse.message);
                        if (code == 1) {
                            nickName = content;
                            tvNickName.setText(content);
                            SharedPreferencesUtils.set(UserInfoActivity.this, SharedPreferencesUtils.SpEnum.LoginNickName, content);
                        } else if (code == 2) {
                            getUserInfo();
                        } else if (code == 3) {
                            birthday = content;
                            tvBirthday.setText(content);
                            SharedPreferencesUtils.set(UserInfoActivity.this, SharedPreferencesUtils.SpEnum.LoginBirthday, content);
                        } else if (code == 4) {
                            sex = Integer.parseInt(content);
                            tvSex.setText(sex == 0 ? "女" : "男");
                            SharedPreferencesUtils.set(UserInfoActivity.this, SharedPreferencesUtils.SpEnum.LoginSex, sex);
                        }
                        dissmissLoadingDialog();
                    }

                    @Override
                    public void onFail(String message, DefaultResponse response) {
                        dissmissLoadingDialog();
                        toast(message);
                    }
                }).start(new DefaultResponse());
    }


    @SuppressWarnings("unchecked")
    private void uploadImg(final String uri) {
        showLoadingDialog();
        new HttpRequest<UploadFileResponse>()
                .with(this)
                .setApiCode(ApiCst.upload)
                .setFile(new File(uri))
                .addFileParam("token", App.getToken(mContext))
                .setListener(new HttpRequest.OnNetworkListener<UploadFileResponse>() {
                    @Override
                    public void onSuccess(UploadFileResponse response) {
                        changeInfo(response.getPhoto(), 2);
                        dissmissLoadingDialog();
                    }

                    @Override
                    public void onFail(String message, UploadFileResponse response) {
                        toast(message);
                        dissmissLoadingDialog();
                    }
                })
                .upload(new UploadFileResponse());
    }


    @SuppressWarnings("unchecked")
    private void getUserInfo() {
        new HttpRequest<UserInfoResponse>()
                .with(this)
                .setApiCode(ApiCst.userinfo)
                .addParam("token", App.getToken(mContext))
                .setListener(new HttpRequest.OnNetworkListener<UserInfoResponse>() {

                    @Override
                    public void onSuccess(UserInfoResponse response) {
                        SharedPreferencesUtils.setUser(UserInfoActivity.this, response.userInfoModel);
                        initDates();
                    }

                    @Override
                    public void onFail(String message, UserInfoResponse response) {

                    }
                }).start(new UserInfoResponse());


    }


    @SuppressWarnings("unchecked")
    private void loginOut() {
        new HttpRequest<DefaultResponse>()
                .with(this)
                .setApiCode(ApiCst.logout)
                .addParam("token", App.getToken(mContext))
                .setListener(new HttpRequest.OnNetworkListener() {

                    @Override
                    public void onSuccess(BaseResponse response) {

                    }

                    @Override
                    public void onFail(String message, BaseResponse response) {

                    }
                }).start(new DefaultResponse());


    }
}
